// 公共的js（比如弹出框，提示）
//region 导入兼容依赖库
if(!JSON){
    //导入json库，方便进行json转换
    $.getScript(__public+"/mobile/js/json2.js");
}
//endregion
//region 公共变量
var curGeolocation;//当前地理位置
//endregion
//region 公共函数
function ismob() {
    ///<summary>判断请求是否来自手机、平板等</summary>
    var match = navigator.userAgent.match(/(iphone|iPod|iPad|android|ios|windows phone)/i);
    return match != null;
}
// 88888888888888888888888888
function eventselector(pcEvent, mobEvent,namesplace) {
    //namesplace提供了绑定事件的命名空间，可以防止意外解绑非目标事件处理程序
    namesplace=namesplace?'.'+namesplace:"";
    if (ismob()) {

        return mobEvent+namesplace;
    }
    return pcEvent+namesplace;
}
//PC、手机事件映射
function eventMap(event,namesplace){
    //namesplace提供了绑定事件的命名空间，可以防止意外解绑非目标事件处理程序
    namesplace=namesplace?'.'+namesplace:"";
    event_maps={"click":"touchend","mousemove":"touchmove","mousedown":"touchstart","mouseup":"touchend"}
    if(ismob() && event_maps[event])
        event=event_maps[event];
    return event+namesplace;
}
//获取标签中指定的回调函数实例
function getCallbackFun(sender) {
    var strcallback = sender.attr("data-callback");
    function callback(e) {
        return true;
    };
    if (strcallback) {
        try{
            callback = eval(strcallback);
            if(typeof(callback)!="function")
                return function(){return true;};
        }catch(ex){
            return function(){return true;}
        }

    }
    return callback;
}
//执行动画
var drawerAnimate = function (obj, location, options) {
    if (!obj || obj.size()==0) {
        return;
    }
    if (location != 0) {
        location = -obj.width();
    }
    var drawlen = obj.width();
    options = $.extend({ step: 0, stepcallback: function () {
    }, callback: function () {
    }, duration: 300
    }, options);
    //计算每步应走多少
    if (options.step == 0) {
        options.step = drawlen / options.duration;
    }
    if (location < 0) {
        options.step = -options.step;
    }
    //重新计算时间
    var stepdura = options.duration * Math.abs(options.step) / drawlen;
    var right = obj.css("right");
    right = Number(right.replace("px", ""));
    var interval = setInterval(function () {
        right += options.step;
        obj.css({ right: right });
        options.duration -= stepdura;
        options.stepcallback.call(obj);
        if (options.duration <= 0) {
            options.duration = 0;
            if (right != location) {
                obj.css({ right: location });
            }
            clearInterval(interval);
            options.callback.call(obj);
        }
    }, stepdura);
};
//获取地理位置
//使用浏览器本身的地理位置定位功能
function getGeolocation(callback){
    if (window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(function (pos) {
            callback({ lng: pos.coords.longitude, lat: pos.coords.latitude });
        }, function (err) {
            getBDGeolocation(callback);
        });
    }else{
        getBDGeolocation(callback);
    }
}
//使用百度地图提供的地理位置定位功能
function getBDGeolocation(callback){
    function getCurrentPosition(){
        window.bd_geolocation.getCurrentPosition(function(r){
            if(this.getStatus() == BMAP_STATUS_SUCCESS){
                callback({ lng: r.point.lng, lat:r.point.lat });
            }
            else {
                //alert('failed'+this.getStatus());
            }
        },{enableHighAccuracy: true})
    }
    if(!window.bd_map_loaded){
        var script=document.createElement("script");
        script.id="bd_map";
        script.onload=function(){
            var div=$("#getBdGeolocation");
            if(div.size()==0){
                $("<div id='getBdGeolocation' style='width:0;height:0'></div>").appendTo("body");
            }
            if(!window.bd_geolocation){
                var map = new BMap.Map("getBdGeolocation");
                var point = new BMap.Point(116.331398,39.897445);
                map.centerAndZoom(point,12);

                window.bd_geolocation = new BMap.Geolocation();
            }
            getCurrentPosition();
            window.bd_map_loaded=true;
        }
        var h=document.getElementsByTagName("head")[0];
        h.appendChild(script);
        //script.src="http://api.map.baidu.com/api?v=2.0&ak="+__baiduak;
        script.src="http://api.map.baidu.com/getscript?v=2.0&ak="+__baiduak+"&services=&t=20160202171524";
    }else{
        getCurrentPosition();
    }


}
//上报地理位置
function reportGeolocation(callback){
    getGeolocation(function(loc){
        if(curGeolocation!=loc){
            curGeolocation=loc;
            //写入到cookie中
            $.cookie("curGeoLocation", JSON.stringify(loc),{expires:1,path:"/"});
            if(callback)
                callback(loc);
        }
    });
}
//将指定的微秒数转为天数
var getTimeSpan=function (milliseconds) {
    ///<summary>时间间隔</summary>
    ///<param name="" type="Number">毫秒数</param>
    var day = Math.floor(milliseconds / (24 * 60 * 60 * 1000));
    var mod = milliseconds % (24 * 60 * 60 * 1000)
    var hours = Math.floor(mod / (60 * 60 * 1000));
    mod = mod % (60 * 60 * 1000);
    var minutes = Math.floor(mod / (60 * 1000));
    mod = mod % (60 * 1000);
    var seconds = Math.ceil(mod / (1000));
    return (day != 0 ? day + "天" : "") + (hours != 0 ? hours + "时" : "") + (minutes != 0 ? minutes + "分" : "") + (seconds != 0 ? seconds + "秒" : "");
}

//endregion
//region jQuery扩展
$.fn.extend(
    {
        //自动滚动加载下一页内容
        autoload:function(options){
            options= $.extend({
                pageInfo:{PageSize:0,CurPageIndex:0,PageCount:0,RowCount:0},//分页信息
                page_var:"p",//分页变量
                url:null,//请求地址
                datatype:"html",//响应类型
                obj:this,//关连对象
                selector:"",//选择器，该设置只有在datatype=html时有效
                autoload:true,//自动加载
                autoload_model:1,//自动加载模式：1绑定屏幕滚动事件，2用户滑动屏幕到底部时加载
                callback:function(){return true;}//回调函数，如果返回true,则继续调用其它后面的代码，返回false，则结束调用
            },options);

            function Loader(ops){
                this.url=ops.url;
                this.pageInfo=ops.pageInfo;
                this.page_var=ops.page_var;
                this.datatype=ops.datatype;
                this.callback=ops.callback;
                this.selector=ops.selector;
                this.autoload=ops.autoload;
                this.obj=$(ops.obj);
                this.path="";//请求路径
                this.data=null;//请求参数
                this.loading=false;//正在加载中
                this.event_binded=false;//是否已经绑定事件
                this.window_height=$(window).height();
                this.init=function(data){
                    data=data || {};
                    //设置当前读取url
                    if(!this.url || this.url=="")
                        this.url=location.href;
                    //分解路径与参数
                    this.path=this.url;
                    var index=this.url.indexOf("?");
                    var params="";
                    if(index>0){
                        this.path=this.url.substring(0,index);
                        params=this.url.substring(index);
                    }
                    this.data={};
                    if(params){
                        var regex=new RegExp("(\\w+)=([^&]+)","g");
                        var matchs=null;
                        while((matchs=regex.exec(params))!=null){
                            this.data[matchs[1]]=matchs[2];
                        }
                    }
                    this.data= $.extend(this.data,data);
                    if(this.pageInfo.PageCount<=1)
                        this.remove();
                }
                this.getUrl=function(){
                    if(this.pageInfo.PageCount<=1 || this.pageInfo.CurPageIndex>=this.pageInfo.PageCount){
                        return false;
                    }
                    var str_params="";
                    var flag=false;//标志参数对象中是否已经有分页变量
                    for(var k in this.data){
                        if(k==this.page_var){
                            flag=true;
                            str_params+="&"+k+"="+(this.pageInfo.CurPageIndex+1);
                        }else{
                            str_params+="&"+k+"="+this.data[k];
                        }

                    }
                    if(!flag){
                        str_params+="&"+this.page_var+"="+(this.pageInfo.CurPageIndex+1);
                    }
                    return this.path+(str_params?"?"+str_params:"");
                }

                this.load=function(url){
                    var _this=this;
                    //加载数据
                    _this.loading=true;
                    $.post(url,{},function(res,status){
                        _this.loading=false;
                        if(status!="error"){
                            _this.pageInfo.CurPageIndex++;
                            //去掉script脚本
                            if(_this.datatype=="html")
                                res=res.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"");
                            var flag=_this.callback.call(_this.obj[0],res,_this.pageInfo);
                            if(flag==false){
                                return;
                            }
                            //默认认为返回的是html片断
                            if(_this.datatype=="html"){
                                var result= null;
                                if(_this.selector){
                                    var temp=$("<div></div>").html($.trim(res)).find(_this.selector);
                                    if(temp.length>0)
                                        result=temp;
                                    else
                                        result=$(res);
                                }else
                                    result=$(res);
                                result.insertBefore(_this.obj);
                            }
                            if( (_this.pageInfo.CurPageIndex+1)> _this.pageInfo.PageCount)
                                _this.remove();
                        }
                    },_this.datatype);
                }


                this.remove=function(){
                    this.obj.hide();
                }
                this.nextPage=function(){
                    //加载下一页
                    var url=this.getUrl();
                    if(!url){
                        return false;
                    }
                    this.load(url);
                }

                this.reload=function(){
                    //重新开始加载
                    this.pageInfo.CurPageIndex=0;
                }


                this.start=function(){
                    if(!this.autoload)
                        return;//不启用滚动自动加载功能
                    var _this=this;
                    if(!this.event_binded) {
                        var win = $(window);
                        if (options.autoload_model !=2) {
                            //屏幕滚动时自动加载
                            win.scroll(function (e) {
                                //判断元素是否可见
                                if (_this.obj.is(":hidden"))
                                    return;//隐藏则不处理
                                //计算加载控件是否在视窗内
                                var cur_top = _this.obj.offset().top;
                                var scroll_top = win.scrollTop();
                                if (cur_top - scroll_top <= _this.window_height+50 && !_this.loading) {
                                    //进入视窗，开始加载
                                    _this.nextPage();
                                }
                            });
                        }else{
                            var begin_y=0;
                            win.on(eventMap("mousemove","autoload"),function(e){
                                //判断元素是否可见
                                if (_this.obj.is(":hidden"))
                                    return;//隐藏则不处理
                                //计算加载控件是否在视窗内
                                var cur_top = _this.obj.offset().top;
                                var scroll_top = win.scrollTop();
                                if (cur_top - scroll_top <= _this.window_height+50 && !_this.loading) {
                                    //进入视窗，开始加载
                                    _this.nextPage();
                                }
                            });
                        }
                        _this.event_binded=true;
                    }

                }
                //最后初始化
                this.init();
            }

            //实例化加载器
            var loader=new Loader(options);
            loader.start();
            //返回当前加载器
            return loader;
        },
        shake:function(count){
            var sender=$(this);
            var i=0;
            //记录原始值
            var pos=sender.css("position");
            var top=sender.css("top");
            var left=sender.css("left");
            sender.css({"position":"relative"});
            var h=setInterval(function(){
                sender.css({"left":(i%2==0?-2:2)+"px","top":(i%2==0?-2:2)+"px"});
                if(i>=count){
                    sender.css({"position":pos,"top":top,"left":left});
                    clearInterval(h);
                }
                i++;
            },30);
        }

    }
);
//endregion

//处理轨迹
var TrackClass = function () {
    var track = function () {
        this.paths = [];
        this.withOuts = ["order.html","Order/index.html", "tuangouorder.html",  "orderSuccess.html", "login.html","ok_order","dz_res.html",
            "account_confirm.html","reset_mob.html","edit_my_info_item.html","modify_my_pic.html","modify_pwd.html","UnitCenter/order_info","UnitCenter/order_info.html"];
    };
    document.createElement("meta")
    track.prototype.key = "trackPaths";
    track.prototype.step = function (path) {
        if (!path) {
            return 0;
        }
        var step = 0;
        if (this.is_ignore(path)) {
            for (var i = 0; i < this.paths.length; i++) {
                if (path == this.paths[i]) {
                    path = this.paths[i - 1];
                    break;
                }
            }
            return step += 1 + this.step(path);
        }
        return step;
    }
    track.prototype.back = function () {

        this.paths = this.getPaths();

        if (!this.paths || this.paths.length == 0) {
            window.location = __indexUrl__?__indexUrl__:"/";
            return;
        }
        var i = this.paths.length - 2;
        if(this.paths[i+1]!=location.href){
            i++;
        }
        var path = this.paths[i];
        var step = this.step(path);
        if (step != 0) {
            path = this.paths[i - step];
        }
        if (!path) {
            window.location.href = __indexUrl__?__indexUrl__:"/";
            return;
        }
        this.paths.splice(i, 2);
        this.save();
        window.location.href = path;
    }
    track.prototype.save = function () {
        var strpaths = "";
        for (var i = 0; i < this.paths.length; i++) {
            if (i > 0) {
                strpaths += ",";
            }
            strpaths += this.paths[i];
        }
        window.sessionStorage.setItem(this.key, strpaths);
    }
    track.prototype.is_ignore=function(path){
        for (var i = 0; i < this.withOuts.length; i++) {
            //var paths=path.split(/(\/)|(\\)/);
            //paths=paths.pop();
            var reg=new RegExp(this.withOuts[i]+"$");
            if (reg.test(path)) {
                return true;
                break;
            }
        }
        return false;
    }
    track.prototype.addPath = function (path) {
        //去掉参数部分
        if (path.indexOf("?") > 0) {
            path = path.substring(0, path.indexOf("?"));
        }
        this.paths = this.getPaths();
        var added = false;
        var index = 0;
        for (var i = 0; i < this.paths.length; i++) {
            if (path == this.paths[i]) {
                added = true;
                index = i;
                break;
            }
        }
        if (added) {
            this.paths.splice(index, 1);
        }
        //var without = false;
        if (!this.is_ignore(path)) {
            this.paths.push(path);
            this.save();
        }
    }
    track.prototype.getPaths = function () {
        var strpaths = window.sessionStorage.getItem(this.key);
        strpaths = strpaths || "";
        this.paths = strpaths.split(",");
        if (!this.paths || this.paths == "") {
            this.paths = [];
        }
        return this.paths;
    }
    track.prototype.init = function () {
        var path = window.location.href;
        this.addPath(path);
    }
    var t = new track();
    t.init();
    return t;
}
//定义一个轨迹
var track = new TrackClass();

//region 就绪事件
$(document).ready(function () {
    // 动态滚动加载图片
    $(".scrollLoading").scrollLoading();
    // 返回上一页
    $('.fh_btn').on('click',function(e){
        //e.preventDefault();
        if($(this).attr('data-no_back') == 1){
            return;
        }
        track.back();
    });
    //处理链接
    var curSender = null;
    var timerid = null;
    var moving_s_y=0;//判断当前是否在滚动，如果是，则相应使用touchend绑定的事件，不应继续处理
    var moveing_e_y=0;
    if(ismob()){
        $(window).on("touchstart.global",function(e){
            moveing_e_y=moving_s_y= e.clientY || e.pageY || e.originalEvent.touches[0].clientY;
        }).on("touchmove.global",function(e){
            moveing_e_y= e.clientY || e.pageY || e.originalEvent.touches[0].clientY;
        }).on("touchend.global",function(){
            moving=false;
        })
    }

    $(document).on(eventMap("click"), "[data-role='href']", function (e) {
        //处理链接跳转
        e.preventDefault();
        var _this=this;
        var sender = $(this);
            if(Math.abs(moveing_e_y-moving_s_y)>20)//非左键则不处理
                return false;
            var callback = getCallbackFun(sender);
            //指向链接之前先执行回调函数
            if (callback.call(_this, e)) {
                var href = sender.attr("data-href");
                if (href) {
                    location.href = href;
                }
            };
            if (curSender != null) {
                curSender.removeClass("focus");
            }

    });

    //处理tab
    $("[data-role='tab']",document).each(function(){
        var tab=$(this);
        var visible = Number( tab.attr("data-visible") || "-1");//显示哪个tab_panel，-1表示都不显示 -2表示都显示
        var animate = tab.attr("data-animate");
        var callback = getCallbackFun(tab);
        var toggle = Number(tab.attr("data-toggle") || "1");//自身是否作为开关使用
        var onClass = tab.attr("data-class") || "onclass";
        var offClass="";
        if(onClass){
            onClass=onClass.split(",");
            if(onClass.length>1 && onClass[1]!=""){
                offClass=onClass[1];
                onClass=onClass[0];
            }else{
                onClass=onClass[0];
            }
        }
        if(visible==-1){
            tab.find("[data-role='tab_head']").removeClass(onClass).addClass(offClass).each(function(){
                $($(this).attr("data-panel")).hide();
            });
        }else{
            tab.find("[data-role='tab_head']").removeClass(onClass).addClass(offClass).each(function(){
                $($(this).attr("data-panel")).hide();
            });
            $(tab.find("[data-role='tab_head']").eq(visible).removeClass(offClass).addClass(onClass).attr("data-panel")).show();
        }
        //给加上索引
        tab.find("[data-role='tab_head']").each(function(i){
            $(this).attr("data-index",i);
        });
        $(this).on(eventMap("click"), "[data-role='tab_head']", function (e) {
            e.preventDefault();
            if(Math.abs(moveing_e_y-moving_s_y)>20){//非左键则不处理
                return;
            }
            var sender = $(this);
            var panel = $(sender.attr("data-panel"));
            var index=sender.attr("data-index");
            var ori_index=tab.find("[data-role='tab_head']."+onClass).attr("data-index");
            //将当前项点亮
            var obj=null;
            tab.find("[data-role='tab_head']:not(:eq("+index+"))").removeClass(onClass).addClass(offClass).each(function(){
                obj=$($(this).attr("data-panel"));
                if(animate=="slide")
                    obj.slideUp();
                else{
                    obj.hide();
                }
            });
            obj=$(sender.attr("data-panel"));
            if(index==ori_index && toggle){
                //当点击的是当前选中项时，则反转开关
                sender.addClass(offClass).removeClass(onClass);
                if(animate=="slide")
                    obj.slideUp();
                else{
                    obj.hide();
                }
            }else{
                sender.addClass(onClass).removeClass(offClass)
                if(animate=="slide")
                    obj.slideDown();
                else{
                    obj.show();
                }
            }
            callback.call(this, e);
        });
    });
    //处理抽屉
    $(document).on(eventMap("click"), "[data-role='drawer']", function () {
        if(Math.abs(moveing_e_y-moving_s_y)>20){//非左键则不处理{
            return;
        }
        var sender = $(this);
        var panel = sender.attr("data-panel");
        if (!panel) {
            return;
        }
        var scroll=sender.attr("data-scroll") || "auto";
        panel = $(panel);
        var fixed = sender.attr("data-fixed");
        if (!fixed) {
            fixed = "left";
        }
        var mask = sender.attr("data-mask") || "none";

        if (mask=="auto") {
            mask = "<div id='drawermask' class=\"leftmask\" style='width:100%;height:100%;position:absolute;top:0;left:0;'></div>";
            $(mask).appendTo("body").height($(document).height());
            sender.attr("data-mask", "#drawermask");
        }
        var zindex = 100000;
        mask = $(mask).css({ zIndex: (zindex - 1) });
        var position=sender.attr("data-position") || "absolute";
        var style={ position: position, zIndex: zindex };
        if(fixed!="bottom"){
            style.top=0;
        }
        panel.css(style);

        var handle = sender.attr("data-handle");
        if (!handle) {
            handle = mask;
        } else {
            handle = $(handle);
        }
        var visible = Number(sender.attr("data-visible"));
        if (!visible) {
            visible = 0;
            sender.attr("data-visible", 0);
        }
        var time = 500;
        var win=$(window);
        var w_w=win.width();
        var w_h=win.height();
        var pw = (fixed=="left" || fixed=="right" ?Math.max(panel.width(),w_w):Math.max(panel.height(),w_h));
        var mw = (fixed=="left" || fixed=="right" ?Math.max(mask.width(),w_w):Math.max(mask.height(),w_h));
        var t = time * pw / mw;
        var offset = mw - pw;
        var step = 20;
        if (visible == 0) {
            var data={display: "block",opacity:0};
            data[fixed]=-pw;
            panel.css(data);
            data[fixed]=-mw;
            mask.css(data);
            data={opacity:1};
            data[fixed]=0;
            panel.animate(data, time);
            mask.animate(data, t);
        }
        handle.unbind(eventMap("click")).on(eventMap("click"), function (e) {
            e.preventDefault();
            var data={opacity:0};
            data[fixed]=-pw;
            panel.animate(data, time, function () {
                $(this).hide();
            });
            data[fixed]=-mw
            mask.animate(data, t, function () {
                $(this).hide();
            });
        });
        //如果是手机的话，去掉window滑动事件,抽屉的滑动由代码实现
        if(ismob() && scroll=="auto"){
            var b_y= 0,p_y= 0,e_y= 0,b_time=0;
            var h=null;
            panel.on("touchstart",function(e){
                e= e.originalEvent.targetTouches[0];
                b_y= e.clientY;
                p_y=panel.scrollTop();
                b_time=(new Date()).getTime();
                if(h){
                    clearInterval(h);
                }
            }).on("touchmove",function(e){
                //e.preventDefault();
                var t= e.originalEvent.targetTouches[0];
                e_y= t.clientY;
                panel.scrollTop(p_y-(e_y-b_y));
                //e.preventDefault();
            }).on("touchend",function(e){
                //e.preventDefault();
                var e_time=(new Date()).getTime();
                var t_off=e_time-b_time;
                if(t_off<300 && Math.abs(e_y-b_y)>100){
                    //console.log(t_off);
                    //如果滑动时间小于600毫秒，则启用快速滑动功能
                    var b_t=panel.scrollTop();
                    var d=e_y-b_y;//方向
                    d=d/Math.abs(d);
                    var distance=d>0?panel[0].scrollHeight-b_t:b_t;
                    var drag=10;//阻力
                    var speed=distance/drag;//速度
                    if(h){
                        clearInterval(h);
                    }
                    h=setInterval(function(){
                        distance-=speed;
                        b_t-=d*speed;
                        panel.scrollTop(b_t);
                        //console.log(b_t+"___"+speed+"________"+distance);
                        if(speed==0 ||distance<=0){
                            clearInterval(h);
                        }else{
                            speed=distance/drag;
                            speed=speed>0?Math.floor(speed):Math.ceil(speed);
                        }
                    },50);
                }
            });

        }

    });

    //处理星级评论
   $("[data-role='star']").each(function(){
       var sender=$(this);
       var val=Number(sender.attr("data-value") || "0");
       sender.css({width:val+'%'});
   });

    //处理发送手机验证码
    $(document).on("click","[data-role='mobVCode']",function(e){
        e.preventDefault();
        var sender=$(this);
        var that=this;
        if(sender.attr("disabled")){
            return;
        }
        function onMessage(e){
            var callback=sender.attr("data-onmessage");
            var r=false;
            if(callback){
                var f=eval(callback);
                if(f){
                    r=f.call(that,e);
                }
            }
            if(!r){
                zk_alert_msg(e.msg);
            }
        }
        var v=$(sender.attr("data-mob"));
        var mob= v.val() || "";
        if(!$.validator.is_mob(mob)){
            onMessage({"source":v[0],"msg":"请输入正确的手机号码"});
            return;
        }
        //var text1=sender.attr("data-text") || "发送验证码";
        var text2=sender.attr("data-text2") || "{time}秒后重新获取";
        var text3=sender.attr("data-text3") || "重新发送";
        var time=parseInt( sender.attr("data-time") || '60');
        $.ajax({
            url:"/Share/send_mobile_vcode",
            dataType:"json",
            type:"get",
            data:{"mob":mob},
            beforeSend:function(){
                sender.attr({disabled:"disabled"});
            },
            success:function(res){
                if(res.status==1){
                    //开始计时
                   var t=text2.replace("{time}",time);
                    sender.text(t).val(t);
                    var h=setInterval(function(){
                        t=text2.replace("{time}",--time);
                        sender.text(t).val(t);
                        if(time==0){
                            clearInterval(h);
                            sender.removeAttr("disabled").text(text3).val(text3);
                        }
                    },1000);
                }else{
                    onMessage(res.msg);
                    sender.removeAttr("disabled").text(text3).val(text3);
                }
            },
            error:function(){
                sender.removeAttr("disabled").text(text3).val(text3);;
            }
        })
    });
    //处理收藏
    $("[data-role='favorites']").on("click",function(e){
        e.preventDefault();
        var sender=$(this);
        var type=sender.attr("data-type");
        if(!type){
            alert("未定义收藏类型");
            return;
        }
        //要收藏的对象id，如果是组合对象，则多个id间使用下划线分割
        var id=sender.attr("data-id");
        if(!id){
            alert("未提供要收藏的对象ID")
        }
        var title=sender.attr("data-title");
        if(!title){
            alert("未提供要收藏的对象标题")
        }
        $.ajax({
            url:"/Share/favorites",
            type:"post",
            dataType:"json",
            data:{type:type,obj_id:id,url:location.href,title:title},
            success:function(res){
               if(res.status==-1){
                   //用户未登录
                   zk_confirm_msg("您未登录，是否立即登录?",function(){
                      //转到登录页面
                       location.href="/Login/index.html";
                   });
               }else{
                   zk_alert_msg(res.msg);
               }
            }
        })
    });

    //处理分享
    $(document).on("click","[data-role='share']",function(e){
        e.preventDefault();
        var sender=$(this);
            var sh_text=sender.attr("data-text");
            var sh_desc=sender.attr("data-desc");
            var sh_url=sender.attr("data-url");
            var sh_pic=sender.attr("data-pic") ;

            if(__refererType__=="weixin"){
                //启用微信的分享功能
                var mask=$("#share_mask");
                var h;
                if(mask.size()==0){
                    mask= $('<div id="share_mask" style="width:100%;height:100%;position: fixed;top:0;left:0; background-color: #000;opacity: 0.8;z-index: 999999"><img style="width:100%;" src="/Public/mobile/images/share_mask.png"/></div>')
                        .css({opacity:0.8})
                        .appendTo("body")
                        .on("click",function(e){
                            e.preventDefault();
                            $(this).hide();
                            if(h){
                                clearTimeout(h);
                            }
                        });
                    //alert(h.html());
                }
                mask.show();
                h= window.setTimeout(function(){
                    mask.hide();
                    clearTimeout(h);
                },1000*3);
            }else{

                if(!window.share_configs){
                    window.share_configs=[];
                }
                var i=window.share_configs.length;
                var config={};
                if(sh_text && sh_desc && sh_url){
                    config={bdText:sh_text,bdDesc:sh_desc,bdUrl:sh_url};
                    if(sh_pic){
                        config.bdPic=sh_pic;
                    }
                }
                window.share_configs.push(config);

                //使用百度的分享功能
                //<div class="bdsharebuttonbox"><a href="#" class="bds_more" data-cmd="more" ></a></div>
               var new_btn= sender.clone().attr({
                    "data-share-index":i,
                    "data-role":"drawer",
                    "data-panel":"#bd_share",
                    "data-fixed":"right",
                    "data-position":"fixed",
                    "data-mask":"none",
                    "data-handle":".bdshare .sh-close"
                }).insertBefore(sender).on(eventMap("click"),function(e){
                   e.preventDefault();
                   var $this=$(this);
                    var id=Number($this.attr("data-share-index"));
                    window.cur_share_config=window.share_configs[id];

               });
                sender.remove();
                if($("#bd_share").size()==0){
                    var share_html='<style type="text/css">' +
                        '.bdshare{text-align: center;position: fixed;width:100%;height:100%;background-color: #f5f5f5}' +
                        '.bdshare ul li.sh-title {background:#0492d3;height:36px;line-height:36px;}' +
                        '.bdshare ul li.sh-close {background:#0492d3;height:36px;line-height:36px;}' +
                        '.bdsharebuttonbox  {text-align: left;}' +
                        '.bdsharebuttonbox  li{width:100%;height:36px;background:#fff;border-bottom:1px solid #eee;margin-bottom:4px;padding-left:20px;}'+
                        '.bdsharebuttonbox  li:first-child {margin-top:4px;}' +
                        '.bdsharebuttonbox  li a{width:100%;margin:0 auto;text-indent:3em;}' +
                        '</style>';
                    share_html+='<div class="bdshare" style="display: none;"  id="bd_share">';
                    share_html+='<ul>';
                    share_html+='<li class="sh-title">分享</li>';
                    share_html+='</ul>';
                    share_html+='<ul class="bdsharebuttonbox" data-tag="share_"'+i+'>';
                    //share_html+='<li ><a class="bds_mshare" data-cmd="mshare"></a></li>';
                    share_html+='<li ><a class="bds_qzone" data-cmd="qzone" >QQ空间</a></li>';
                    share_html+= '<li ><a class="bds_tsina" data-cmd="tsina">新浪微博</a></li>';
                    share_html+='<li ><a class="bds_renren" data-cmd="renren">人人网</a></li>';
                    share_html+='<li ><a class="bds_tqq" data-cmd="tqq">腾讯微博</a></li>';
                    share_html+='</ul>';
                    share_html+='<ul>';
                    share_html+='<li class="sh-close"><a href="javascript:void(0);">取消</a></li>';
                    share_html+='</ul>';
                    share_html+='</div>';
                    $(share_html).appendTo("body");
                    window._bd_share_config={
                        "common":{
                            "bdSnsKey":{},
                            "bdText":"",
                            "bdMini":"2",
                            "bdMiniList":false,
                            "bdPic":"",
                            "bdStyle":"0",
                            "bdSize":"32",
                            "onBeforeClick":function(cmd,config){
                                if(window.cur_share_config){
                                   if(ismob() && cmd=="qzone"){
                                       window.cur_share_config.bdDesc="";
                                       console.log(window.cur_share_config.bdDesc);
                                   }
                                    return window.cur_share_config;
                                }
                                else
                                    return config;
                            }
                        },
                        "share":{},
                        "image":{"viewList":[],"viewText":"分享到：","viewSize":"16"},
                        "selectShare":{"bdContainerClass":null,"bdSelectMiniList":[]}};
                    with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
                }
                //最后触发一次点击
                new_btn.trigger(eventMap("click"));
            }
    });
    //固定底部
    var $footer=$("#footer");
    if($footer.size()==1){
        var h_fixed=setTimeout(function(){
            //这里延迟设置，是为了防止布局还未完成就取得高度。而此时的高度是不正确的
            if($footer.height()+$footer.offset().top<$(window).height()){
                $footer.css({position:"fixed","bottom":0});
                clearTimeout(h_fixed);
            }
        },20)
    }
    //上滑隐藏地址栏。当用户往下拉时，可显示地址栏，该功能在部份浏览器中无效
    $(window).on("load",function(){
        setTimeout(function(){
            window.scrollTo(0,1);
        },0);
    });
    //每10分钟上报一次地理位置
    //var disabled_geo=disabled_geo==undefined?false:disabled_geo;
    //if(!disabled_geo){
        reportGeolocation();
        setInterval(function(){
            reportGeolocation();
        },1000*60*10);
    //}

});
//endregion

// 操作成功弹出框
var zk_success_msg = function(msg,call_fun){
    var index=layer.open({
        title: ['温馨提示','background-color:#0b93d1; color:#fff; text-align:center;'],
        content:'<div>'+msg+'</div>',
        style: 'width:80%;',
        btn: ['确认'],
        time:1.5,
        yes:function(){
            layer.close(index);
            if(call_fun){
                call_fun();
            }
        },
        end:function(){
            //layer.close(index);
            if(call_fun){
                call_fun();
            }
        }
    });
};
// 确认取消弹出框
var zk_confirm_msg = function(msg,y_call,n_call){
    var index=layer.open({
        title: ['温馨提示','background-color:#0b93d1; color:#fff; text-align:center;'],
        content:'<div>'+msg+'</div>',
        style: 'width:80%;',
        shadeClose:false,
        btn: ['确认', '取消'],
        yes: function(){
            layer.close(index);
            if(y_call){
                y_call();
            }
        },
        no: function(){
            layer.close(index);
            if(n_call){
                n_call();
            }
        }
    });
};
// 全局的弹出框提示(有传time=0就要点击空白出消失，如果不传就会在3消失时间)
var zk_alert_msg = function(msg,time,callfun){
    time = time==undefined?3:time;
    var index=layer.open({
        content:msg,
        time:time
    });
    if(callfun){
        setTimeout(function(){
            layer.close(index);
            callfun();
        },2000);
    }
};
// 验证手机
var zk_verify_mobile = function(str){
    var re = /^1[34578]\d{9}$/;
    return re.test(str);

};

//验证车牌号
var zk_verify_carno=function($str){
    var re=/^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/;
    return re.test($str)
}
// 验证身份证
var zk_check_cardno = function(idCard){
    
    if(idCard.length == 15 || idCard.length == 18){
        return true;
    }else{
        return false;
    }


    /*var check_flag = false;
    //15位和18位身份证号码的正则表达式
    var regIdCard=/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(regIdCard.test(idCard)){
        if(idCard.length==18){
            var idCardWi=new Array( 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ); //将前17位加权因子保存在数组里
            var idCardY=new Array( 1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2 ); //这是除以11后，可能产生的11位余数、验证码，也保存成数组
            var idCardWiSum=0; //用来保存前17位各自乖以加权因子后的总和
            for(var i=0;i<17;i++){
                idCardWiSum+=idCard.substring(i,i+1)*idCardWi[i];
            }
            var idCardMod=idCardWiSum%11;//计算出校验码所在数组的位置
            var idCardLast=idCard.substring(17);//得到最后一位身份证号码
            //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if(idCardMod==2){
                if(idCardLast=="X"||idCardLast=="x"){
                    //alert("恭喜通过验证啦！");
                    check_flag = true;
                }else{
                    //alert("身份证号码错误！");
                    check_flag = false;
                }
            }else{
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if(idCardLast==idCardY[idCardMod]){
                    //alert("恭喜通过验证啦！");
                    check_flag = true;
                }else{
                    //alert("身份证号码错误！");
                    check_flag = false;
                }
            }
        } 
    }else{
        //alert("身份证格式不正确!");
        check_flag = false;
    }
    return check_flag;*/
};
// 校验密码：只能输入6-20个字母、数字、下 划线
var zk_is_pwd = function(pwd){
    var reg = /^(?![^a-zA-Z]+$)(?!\D+$).{6,20}$/;
    return reg.test(pwd);
};
// 获取本地缓存数据
var getLocalData = function(key){
    ///<summary>获取本地缓存数据</summary>
    ///<param name="key" type="String">关键字</param>
    var val = "";
    if (window.localStorage) {
        val = window.localStorage.getItem(key);       
    } else {
        val = $.cookie(key);
    }
    return val;
};
// 设置本地缓存数据
var setLocalData = function(key, val, expires, unit){
    ///<summary>设置本地缓存数据</summary>
    ///<param name="key" type="String">关键字</param>
    ///<param name="val" type="String">值</param>
    ///<param name="exprie" type="Number">过期时间,如果浏览器不支持html5的话，则用cookie来保存数据</param>
    ///<param name="unit" type="String">过期单位：second,minute,hour,day,month,year,默认是year</param>
    if (window.localStorage) {       
        window.localStorage.setItem(key, val);
    } else {
        if ( ! expires) {
            expires = 1;
        }
        var exdate = new Date()
        switch (unit) {
            case "year":
                exdate.setFullYear(exdate.getFullYear() + expires);
                break;
            case "month":
                exdate.setMonth(exdate.getMonth() + expires);
                break;
            case "day":
                exdate.setDate(exdate.getDate() + expires);
                break;
            case "hour":
                exdate.setHours(exdate.getHours() + expires);
                break;
            case "minute":
                exdate.setMinutes(exdate.getMinutes() + expires);
                break;
            case "second":
                exdate.setSeconds(exdate.getSeconds() + expires);
                break;
            default:
                exdate.setDate(exdate.getDate() + expires);
        };
                document.cookie = name + "=" + escape(value) +
                ((expires == null) ? "" : ";expires=" + exdate.toUTCString())+";path=/";
        if (!unit) {
            unit = "year";
        }
        $.cookie(key,val,{expires:exdate.toUTCString(),path:'/'});
    }
};
// 全局获取当前城市区号
var get_cur_city_areacode = function(call_fun){
    var areacode = '010';
    //$.ajaxSettings.async = false;
    $.ajax({
        url:'/Share/get_cur_city_areacode',
        dataType:'json',
        success:function(data){
            if(data.status==1){
                call_fun(data.data);
            }else{
                zk_alert_msg('暂时定位不到您的地理位置')
            }
            return;
        }
    });
    return areacode;
};